package cn.isaac.firstkotlin.adapter

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.isaac.firstkotlin.R
import cn.isaac.firstkotlin.domain.Forecast
import cn.isaac.firstkotlin.domain.ForecastList
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_forecast.view.*

/**
 * Created by RaoWei on 2017/5/22 10:17.
 */

class ForecastListAdapter2(val weekForecast: ForecastList, val itemClick: (Forecast) -> Unit) : RecyclerView.Adapter<ForecastListAdapter2.ViewHolder>() {
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindForecast(weekForecast[position])
    }

    override fun getItemCount() = weekForecast.size()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflate = LayoutInflater.from(parent.context).inflate(R.layout.item_forecast, parent, false)
        return ViewHolder(inflate, itemClick)
    }

    class ViewHolder(view: View, val itemClick: (Forecast) -> Unit) : RecyclerView.ViewHolder(view) {
        fun bindForecast(forecast: Forecast) {
//        with是一个非常有用的函数，它包含在Kotlin的标准库中。它接收一个对象
//        和一个扩展函数作为它的参数，然后使这个对象扩展这个函数。这表示所
//        有我们在括号中编写的代码都是作为对象（第一个参数）的一个扩展函
//        数，我们可以就像作为this一样使用所有它的public方法和属性。当我们针
//        对同一个对象做很多操作的时候这个非常有利于简化代码。
            with(forecast) {
                Picasso.with(itemView.context).load(iconUrl).into(itemView.icon)
                itemView.date.text = date
                itemView.description.text = description
                itemView.maxTemperature.text = "${high}º"
                itemView.minTemperature.text = "${low}º"
                itemView.setOnClickListener { itemClick(this) }
            }
        }
    }

}